import { filter } from 'rxjs/operators';
import { Observable } from 'rxjs';
/**
 * 取每第N个值的操作符
 */
export const takeEveryNth =
  (n: number) =>
  <T>(source: Observable<T>) =>
    new Observable<T>((observer) => {
      let count = 0;
      return source.subscribe({
        next(x) {
          if (count++ % n === 0) observer.next(x);
        },
        error(err) {
          observer.error(err);
        },
        complete() {
          observer.complete();
        },
      });
    });

/**
 * 还可以使用现有的操作符
 */
export const takeEveryNthSimple =
  (n: number) =>
  <T>(source: Observable<T>) =>
    source.pipe(filter((value, index) => index % n === 0));

/**
 * 因为 pipeable 操作符返回的是函数，还可以进一步简化
 */
export const takeEveryNthSimplest = (n: number) =>
  filter((value, index) => index % n === 0);
